package LeetCode;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/4/30.
//
//https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
public class 删除链表的倒数第N个节点 {
    public static class ListNode{
        int val;
        ListNode next;
        ListNode(){};
        ListNode(int val,ListNode next){this.val = val;this.next = next;}

        @Override
        public String toString() {
            return val + "," + next;
        }
    }

    public static void main(String[] args) {
//        ListNode head = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5,null)))));
        ListNode head = new ListNode(1,null);
        System.out.println("[" + removeNthFromEnd(head,1) + "]");
    }
    public static ListNode removeNthFromEnd(ListNode head,int n){
        ListNode sentry = new ListNode(0,head);
        findPreNode(sentry,n+1);
        return sentry.next;
    }

    private static int findPreNode(ListNode node, int n) {
        if(node == null)return 0;
        int num = findPreNode(node.next,n) + 1;
        if(num == n){
            node.next = node.next.next;
        }
        return num;
    }
}
